import TauPage from '@/components/TauPage';
import TauActionPanel from '@/components/TauActionPanel';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Dialog, Drawer, Message, Button, Checkbox } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useRef, useState, useEffect } from 'react';
import CouponForm from './components/CouponForm';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import { toJS } from 'mobx';
import RelevancyActivity from './components/RelevancyActivity';
import BatchApply from './components/BatchApply';
import BatchApplyTable from './components/BatchApplyTable';

const tableId = uniqueId('tauTable-');

function Coupon() {
  const [modal, setModal] = useState([]);
  const [showBatch, setShowBatch] = useState(false);
  const [counts, setCounts] = useState([]);
  const { couponStore: store } = useStore();
  const objRef = useRef(); // 当前选中的对

  useEffect(() => {
    if (showBatch) {
      (async () => {
        const res = await fetchBatchCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [store.data, showBatch]);

  // 获取订单
  async function fetchBatchCounts() {
    const promiseAry = store.data.map(async (p) => {
      return store.api.getBatchCount({
        search: {
          batchIds: [p.id],
        },
      }).then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { upDate, ...searchArgs } = params.values;
    const [from, to] = upDate || [];
    store.search = {
      from,
      to,
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    objRef.current = {};
    setModal(['add']);
  };

  // 点击打开编辑
  const handleOpenEdit = (current) => {
    objRef.current = current;
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 创建活动
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create({ ...toJS(result) });
        Message.success({ content: t`卡券创建成功` });
      } catch (e) {
        Message.error({ content: t`卡券创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 删除活动
  const handleRemoveActivity = (record) => {
    Dialog.confirm({
      title: t`删除卡券`,
      content: t`确认要删除该卡券吗? 一但删除, 无法撤回!`,
      onOk: async () => {
        try {
          await store.remove(record);
          Message.success({ content: t`卡券删除成功` });
        } catch (error) {
          Message.error({ content: t`卡券删除失败`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  // 查看详情
  const handleOpenView = async (result) => {
    objRef.current = result;
    setModal(['view']);
  };

  // 查看详情
  const handleOpenBatch = async (result) => {
    objRef.current = result;
    setModal(['openBatch']);
  };

  // 新增订单数据提交
  const handleAdd = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update({ ...toJS(result) });
        Message.success({ content: t`白名单添加成功` });
      } catch (e) {
        Message.error({ content: t`白名单添加失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleApplyBatch = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.applyBatch({ ...toJS(result) });
        Message.success({ content: t`批次申领成功` });
      } catch (e) {
        Message.error({ content: t`批次申领失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const relevancyActivitySubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update({ ...toJS(result) });
        Message.success({ content: t`关联活动成功` });
      } catch (e) {
        Message.error({ content: t`关联活动失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeCoupon',
            title: t`创建卡券批次`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        searchItems={[
          {
            name: 'enable',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.enable),
              placeholder: t`启用状态`,
            },
          },
          {
            name: 'upDate',
            type: 'date-range',
            props: {
              placeholder: [t`开始创建时间`, t`结束创建时间`],
            },
          },
        ]}
        extraItems={[
          {
            name: 'cbx-showBatch',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowBatch(v)}>{t`查看批次申领`}</Checkbox>,
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('batchId', {
              width: 148,
              cell: (v, _, activity) => <Button text type="primary" onClick={() => handleOpenView(activity)}>{v}</Button>,
            }),
            column('name', { width: 138 }),
            column('type', { width: 58 }),
            column('rules.面值', { width: 58 }),
            column('rules.业务类型', { width: 72 }),
            column('timeLimit', { width: 88 }),
            column('rules.是否可转赠', { width: 82 }),
            column('couponApplyCount', {
              width: 68,
              cell: (v, _, activity) => <Button type="primary" text onClick={() => handleOpenBatch(activity)}>{counts.find((n) => n.id === activity.id)?.count || 0}</Button>,
            }),
            column('enable', { width: 82 }),
            column('crDate', { width: 98 }),
            {
              title: t`操作`,
              dataIndex: 'activityNumber',
              width: 138,
              cell: (_, i, coupon) => {
                const funcMenu = [
                  {
                    title: '编辑',
                    onClick: () => handleOpenEdit(coupon),
                  },
                  // {
                  //   title: '批次申领',
                  //   onClick: () => handleAddWhiteList(coupon),
                  // },
                  // {
                  //   title: '关联活动',
                  //   onClick: () => handleRelevancyActivity(coupon),
                  // },
                  {
                    title: '删除',
                    onClick: () => handleRemoveActivity(coupon),
                    color: 'red',
                  },
                ];
                return (
                  <>
                    <MoreFuncDropDown
                      dropdownItems={funcMenu}
                      maxShow={2}
                    />
                  </>
                );
              },
            },
          ].filter((c) => c.dataIndex !== 'couponApplyCount' || showBatch)}
        />
      </div>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit' || modal[0] === 'view'}
        title={modal[0] === 'add' ? t`添加批次` : t`修改批次【${objRef.current?.name}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="600px"
      >
        <CouponForm
          id={objRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>

      <Drawer
        visible={modal[0] === 'whiteList'}
        title={t`批次申领`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="600px"
      >
        <BatchApply
          coupon={objRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={handleApplyBatch}
        />
      </Drawer>

      <Drawer
        visible={modal[0] === 'openBatch'}
        title={t`批次申请`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="70%"
      >
        <BatchApplyTable
          coupon={objRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={handleAdd}
        />
      </Drawer>

      <RelevancyActivity
        visible={modal[0] === 'relevancy'}
        coupon={objRef.current}
        onClose={() => {
          setModal([]);
        }}
        onSubmit={relevancyActivitySubmit}
      />
    </TauPage>
  );
}

export default observer(Coupon);
